#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import logging
import optparse
import sys

from oriolusgaffer.gaffer import GafferFactory

# cli.py install agami-1.0.0.0
# cli.py remove agami-1.0.0.0
# cli.py install_local c:\\agami
# cli.py get
# cli.py upgrade

def exit(parser):
    parser.print_help()
    parser.destroy()
    sys.exit(0)
    
def check_args_count(args, number):
    if len(args) != number:        
        exit(parser)    

def run():
    list = ["install", "remove", "install_local", "update_list", "upgrade"]
    usage = """usage: cli.py command [args]
    command:
        install [names] - install packets with specified names
        remove [names] - remove packets with specified names        
        update_list - update index packet on local drive
        upgrade - upgrade all packets if there any"""
    
    parser = optparse.OptionParser(usage=usage, version = "OriolusGaffer 0.1.0")
    parser.add_option("-l", dest = "loglevel", action="count", help = "set logging level, the count of option defines logging level (-l: DEBUG, -ll: INFO, -lll: WARNING, -llll: ERROR, -lllll: CRITICAL)")
    parser.add_option("--log", dest = "logfilename", default = "./gaffer.log.txt", help = "set log file name [default: %default]")
    parser.add_option("-c", "--config", dest = "config", help = "Path for gaffer configuration file")
    
    (options, args) = parser.parse_args()
    
    if len(args) == 0:
        exit(parser)    
    
    flag = False
    for each in args:
        if (not flag) and (each in list):
            flag = True
        elif (flag) and (each in list):
            exit(parser)

    loglevel = 0
    if options.loglevel:
        if options.loglevel > 5:
            options.loglevel = 5
        loglevel = options.loglevel * 10
        logging.basicConfig(level = loglevel, filename = options.logfilename, format = "%(asctime)-15s [%(thread)d] %(levelname)-5s %(name)s - %(message)s", )
    else:
        logging.basicConfig(level = logging.INFO, format = "[%(levelname)s] %(message)s", )

    factory = GafferFactory()
    if options.config:
        gaffer = factory.get_gaffer(options.config)
    else:
        gaffer = factory.get_gaffer()    
    
    command = args[0]
    if command == "install":        
        gaffer.install(args[1:])            
    if command == "remove":         
        gaffer.remove(args[1:])    
    if command == "update_list":
        check_args_count(args, 1)
        gaffer.update_list()
    if command == "upgrade":
        check_args_count(args, 1)
        gaffer.upgrade()
        
if __name__ == "__main__":
    run()
